package com.example.cofeed;

import android.content.Intent;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.os.Bundle;
import android.view.View;

import com.ada.common.widget.NoTouchViewPager;
import com.ada.common.widget.SpecialTab;
import com.blankj.utilcode.util.ActivityUtils;
import com.blankj.utilcode.util.AppUtils;
import com.blankj.utilcode.util.ObjectUtils;
import com.blankj.utilcode.util.SPUtils;
import com.example.cofeed.activity.DetailsActivity;
import com.example.cofeed.activity.LoginActivity;
import com.example.cofeed.activity.MyMsgActivity;
import com.example.cofeed.activity.ReplyCommentsActivity;
import com.example.cofeed.activity.SystemMessagesActivity;
import com.example.cofeed.activity.WebViewActivity;
import com.example.cofeed.activity.fragment.HomeFragment;
import com.example.cofeed.activity.fragment.MsgFragment;
import com.example.cofeed.activity.fragment.MyFragment;
import com.example.cofeed.activity.fragment.DemandFragment;
import com.example.cofeed.api.ApiService;
import com.example.cofeed.base.BaseActivity;
import com.example.cofeed.callback.DialogCallback;
import com.example.cofeed.callback.LzyResponse;
import com.example.cofeed.constant.IntentKeyConstant;
import com.example.cofeed.constant.SputilsConstant;
import com.example.cofeed.entity.VersionBean;
import com.example.cofeed.even.RefreshEven;
import com.example.cofeed.push.HuaweiPushRevicer;
import com.example.cofeed.util.OkGoUpdateHttpUtil;
import com.lzy.okgo.model.Response;
import com.umeng.analytics.MobclickAgent;
import com.vector.update_app.UpdateAppBean;
import com.vector.update_app.UpdateAppManager;
import com.vector.update_app.UpdateCallback;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONArray;
import org.json.JSONException;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import me.majiajie.pagerbottomtabstrip.NavigationController;
import me.majiajie.pagerbottomtabstrip.PageNavigationView;
import me.majiajie.pagerbottomtabstrip.item.BaseTabItem;
import me.majiajie.pagerbottomtabstrip.listener.OnTabItemSelectedListener;

import static com.example.cofeed.push.HuaweiPushRevicer.ACTION_TOKEN;
import static com.example.cofeed.push.HuaweiPushRevicer.ACTION_UPDATEUI;

public class MainActivity extends BaseActivity implements HuaweiPushRevicer.IPushCallback {

    public NavigationController mNavigationController;

    @Override
    protected boolean isNeedTitleBar() {
        return false;
    }

    @BindView(R.id.viewPager)
    NoTouchViewPager mViewPager;
    @BindView(R.id.navigation)
    PageNavigationView mTab;

    private List<Fragment> mFragmentList = new ArrayList<>();

    @Override
    protected int getLayoutId() {
        return R.layout.activity_main;
    }

    @Override
    protected void init(Bundle savedInstanceState, View container) {
        mNavigationController = mTab.custom()
                .addItem(newItem(R.mipmap.na01f, R.mipmap.na01, "首页"))
                .addItem(newItem(R.mipmap.nav02f, R.mipmap.nav02, "供求"))
                .addItem(newItem(R.mipmap.nav03f, R.mipmap.nav03, "短信"))
                .addItem(newItem(R.mipmap.nav04f, R.mipmap.nav04, "我的"))
                .build();

        mFragmentList.add(new HomeFragment());
        mFragmentList.add(new DemandFragment());
        mFragmentList.add(new MsgFragment());
        mFragmentList.add(new MyFragment());

        mViewPager.setAdapter(new MyViewPagerAdapter(getSupportFragmentManager()));
        mViewPager.setOffscreenPageLimit(mFragmentList.size() - 1);
        //自动适配ViewPager页面切换
        mNavigationController.setupWithViewPager(mViewPager);
        mNavigationController.addTabItemSelectedListener(new OnTabItemSelectedListener() {
            @Override
            public void onSelected(int index, int old) {
                if (index == 2 || index == 3){
                    String token = SPUtils.getInstance().getString(SputilsConstant.TOKEN);
                    if (ObjectUtils.isEmpty(token)) {
                        mNavigationController.setSelect(old);
                        ActivityUtils.startActivity(LoginActivity.class);
                        return;
                    }
                }

            }

            @Override
            public void onRepeat(int index) {
                if (index != 3){
                    EventBus.getDefault().post(new RefreshEven(index));
                }
            }
        });

        AppUpdate();
        registerBroadcast();

    }

    private void AppUpdate() {
        ApiService.version(AppUtils.getAppVersionName(), new DialogCallback<LzyResponse<VersionBean>>() {
            @Override
            public void onSuccess(final Response<LzyResponse<VersionBean>> response) {
                if (response.body().data.update > 0) {
                    new UpdateAppManager
                            .Builder()
                            //当前Activity
                            .setActivity(MainActivity.this)
                            //更新地址
                            .setUpdateUrl("https://www.baidu.com/")
                            //实现httpManager接口的对象
                            .setHttpManager(new OkGoUpdateHttpUtil())
                            .build()
                            .checkNewApp(new UpdateCallback() {
                                @Override
                                protected UpdateAppBean parseJson(String json) {
                                    UpdateAppBean updateAppBean = new UpdateAppBean();
                                    updateAppBean
                                            //（必须）是否更新Yes,No
                                            .setUpdate("Yes")
                                            //（必须）新版本号，
                                            .setNewVersion(response.body().data.msg)
                                            .setUpdateDefDialogTitle(response.body().data.msg)
                                            //（必须）下载地址
                                            .setApkFileUrl(response.body().data.updateurl)
                                            //（必须）更新内容
                                            .setUpdateLog("");
                                    return updateAppBean;

                                }
                            });
                }

            }
        });

    }

    /**
     * 以下代码为sample自身逻辑，和业务能力不相关
     * 作用仅仅为了在sample界面上显示push相关信息
     */
    private void registerBroadcast() {
        HuaweiPushRevicer.registerPushCallback(this);
    }

    @Override
    public void onReceive(Intent pushIntent) {
        if (pushIntent != null) {
            String action = pushIntent.getAction();
            Bundle b = pushIntent.getExtras();
            if (b != null && ACTION_TOKEN.equals(action)) {
                String token = b.getString(ACTION_TOKEN);
            } else if (b != null && ACTION_UPDATEUI.equals(action)) {
                String log = b.getString("log");
                JSONArray json = null;
                try {
                    json = new JSONArray(log);

                    String type = json.getJSONObject(0).optString("type");
                    String id = json.getJSONObject(0).optString("id");
                    String url = json.getJSONObject(0).optString("url");
                    if (ObjectUtils.isNotEmpty(type)) {
                        if (type.equals("arcitle")) {
                            Intent intent = new Intent(mContext, WebViewActivity.class);
                            intent.putExtra(IntentKeyConstant.ID, id);
                            intent.putExtra(IntentKeyConstant.URL, url);
                            intent.putExtra(IntentKeyConstant.TYPE, -2);

                            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                            mContext.startActivity(intent);

                        }
                        if (ObjectUtils.isEmpty(SPUtils.getInstance().getString(SputilsConstant.TOKEN))) {
                            ActivityUtils.startActivity(LoginActivity.class);
                            return;
                        }
                        Intent intent = null;
                        switch (type) {
                            //商机消息
                            case "askmsg":
                                intent = new Intent(mContext, ReplyCommentsActivity.class);
                                intent.putExtra(IntentKeyConstant.ID, id);
                                intent.putExtra(IntentKeyConstant.URL, url);
                                intent.putExtra(IntentKeyConstant.TYPE, 2);
                                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
                                mContext.startActivity(intent);
                                break;
                            //咨询回复
                            case "replymsg":
                                intent = new Intent(mContext, ReplyCommentsActivity.class);
                                intent.putExtra(IntentKeyConstant.ID, id);
                                intent.putExtra(IntentKeyConstant.URL, url);
                                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
                                mContext.startActivity(intent);
                                break;
                            //系统消息
                            case "sysmsg":
                                intent = new Intent(mContext, SystemMessagesActivity.class);
                                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
                                mContext.startActivity(intent);
                                break;
                            //评论回复
                            case "sysreply":
                                intent = new Intent(mContext, ReplyCommentsActivity.class);
                                intent.putExtra(IntentKeyConstant.ID, id);
                                intent.putExtra(IntentKeyConstant.URL, url);
                                intent.putExtra(IntentKeyConstant.TYPE, 1);
                                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
                                mContext.startActivity(intent);
                                break;
                            case "sms":
                                Intent i = new Intent(mContext, DetailsActivity.class);
//					i.putExtras(bundle);
                                String smsid = json.getJSONObject(0).optString("smsid");

                                i.putExtra(IntentKeyConstant.MSG_ID, smsid);
                                //i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                                i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                                mContext.startActivity(i);
                                break;

                        }

                    }

//                    int type = json.getJSONObject(0).optInt("type");
//                    String smsid = "";
//                    if (type == 1 && !ObjectUtils.isEmpty(smsid)) {
//                        //打开自定义的Activity
//                        smsid = json.getJSONObject(1).optString("smsid");
//                        Intent i = new Intent(this, DetailsActivity.class);
//                        i.putExtra(ConstantQuantity.MSG_ID, smsid);
//                        i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//                        startActivity(i);
//                    } else if (type == 2) {
//                        Intent i = new Intent(this, MyMsgActivity.class);
//                        //i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//                        i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//                        startActivity(i);
//                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    private class MyViewPagerAdapter extends FragmentPagerAdapter {

        public MyViewPagerAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public Fragment getItem(int position) {
            return mFragmentList.get(position);
        }

        @Override
        public int getCount() {
            return mFragmentList.size();
        }
    }

    /**
     * 正常tab
     */
    private BaseTabItem newItem(int drawable, int checkedDrawable, String text) {
        SpecialTab mainTab = new SpecialTab(this);
        mainTab.initialize(drawable, checkedDrawable, text);
        mainTab.setTextDefaultColor(getResources().getColor(R.color.colorTextNormal));
        mainTab.setTextCheckedColor(getResources().getColor(R.color.titleBgColor));
//        mainTab.setTextDefaultColor(0xFF888888);
//        mainTab.setTextCheckedColor(getResources().getColor(R.color.mainThemeColor));
        return mainTab;
    }

    private long mLastClickBackTime = 0L;

    @Override
    public void onBackPressed() {

        long nowTime = System.currentTimeMillis();
        if (nowTime - mLastClickBackTime < 1000 * 2) {
            super.onBackPressed();
            App.getInstance().exitApp();
        } else {
            showToast("再按一次退出应用");
        }
        mLastClickBackTime = nowTime;
    }


    @Override
    public void onResume() {
        super.onResume();
        MobclickAgent.onResume(this);
    }

    @Override
    public void onPause() {
        super.onPause();
        MobclickAgent.onPause(this);
    }

}